package 有效的井字游戏;

public class Solution {
    public static void main(String[] args) {
        String[] board = new String[]{"XOX", "O O", "XOX"};
        System.out.println(validTicTacToe(board));
    }

    public static boolean validTicTacToe(String[] board) {


        int xCount = 0;
        int oCount = 0;

        for (int i = 0; i < board.length; i++) {
            char[] chars1 = board[i].toCharArray();
            for (int j = 0; j < chars1.length; j++) {
                if (chars1[j] == 'X') {
                    xCount++;
                } else if (chars1[j] == 'O') {
                    oCount++;
                }
            }

        }
        return !((oCount != xCount && oCount != xCount - 1) ||
                (oCount != xCount - 1 && win(board, 'X')) ||
                (oCount != xCount && win(board, 'O')));

    }

    public static boolean win(String[] board, char p) {
        for (int i = 0; i < 3; i++) {
            if (board[i].charAt(0) == p && board[i].charAt(1) == p && board[i].charAt(2) == p ||
                    board[0].charAt(i) == p && board[1].charAt(i) == p && board[2].charAt(i) == p
            ) {
                return true;
            }
        }

        return (board[0].charAt(0) == p && board[1].charAt(1) == p && board[2].charAt(2) == p
                || board[0].charAt(2) == p && board[1].charAt(1) == p && board[2].charAt(0) == p
        );
    }
}
